package com.game.sdk.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;

import com.game.sdk.ChannelUtil;
import com.game.sdk.YTAppService;
import com.game.sdk.db.impl.AgentDbDao;
import com.game.sdk.domain.AgentDbBean;
import com.game.sdk.domain.PaymentCallbackInfo;
import com.game.sdk.domain.PaymentErrorMsg;
import com.game.sdk.domain.ResultCode;
import com.game.sdk.init.NetCallBack;
import com.game.sdk.ui.ChargeActivity;
import com.game.sdk.view.ChargeView;
import com.ta.utdid2.android.utils.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.List;
import java.util.Random;

/**
 * @修改日志 @2.25 增加一个 加qq群的工具函数 joinQQGroup详细使用需要查看函数
 **/
public class Util {

	private static final String TAG = "Util";

	/**
	 * @return
	 */
	public static String getOrderId() {
		String orderId = "" + System.currentTimeMillis();
		return orderId;
	}

	/***
	 * 由于在联网获取数据的失败的时候都会去调用，写出来不用重复写
	 */
	public static void showNetFailToast(Context acontext, String defaultToast, ResultCode result) {
		if (result == null || result.msg == null || result.msg.equals("")) {
			Toast.makeText(acontext, defaultToast, Toast.LENGTH_SHORT).show();
			return;
		}
		Toast.makeText(acontext, result.msg, 0).show();
	}

	/**
	 * 支付请求失败
	 */
	public static void onPayReqFail(String str, double charge_money, Activity atx) {
		ChargeView.ischarge = false;
		PaymentErrorMsg msg_e = new PaymentErrorMsg();
		msg_e.code = -1;
		msg_e.msg = StringUtils.isEmpty(str) ? "请求下单失败了" : str;
		msg_e.money = charge_money;
		ChargeActivity.paymentListener.paymentError(msg_e);
		atx.finish();
		ActivityTaskManager.getInstance().removeActivity("ChargeActivity");
	}

	/**
	 * 支付请求 成功
	 */
	public static void onPayReqSuc(String str, double charge_money, Activity atx) {
		ChargeView.ischarge = false;
		PaymentCallbackInfo msg_e = new PaymentCallbackInfo();
		msg_e.msg = StringUtils.isEmpty(str) ? "请求下单失败了" : str;
		msg_e.money = charge_money;
		ChargeActivity.paymentListener.paymentSuccess(msg_e);
		atx.finish();
		ActivityTaskManager.getInstance().removeActivity("ChargeActivity");
	}

	/***
	 * 这是一个通用的handler network代码
	 */
	public static void netResponseCommHandler(int defaultCode, String result, NetCallBack callback) {
		if (DialogUtil.isShowing()) {// 尝试取消对话框
			try {
				DialogUtil.dismissDialog();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (StringUtils.isEmpty(result)) {// 非空判断
			callback.onInitFail(null);
		} else {
			try {
				JSONObject json;
				json = new JSONObject(result);
				ResultCode code = new ResultCode();
				code.parseCommJson(json);
				if (code.code == defaultCode) {
					callback.onInitSuccess(code);
				} else {
					callback.onInitFail(code);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	/***
	 * 由于支付模块使用平凡 fragment 所以写一个这样的方法'
	 * 
	 * @author ling
	 */
	public static void addFragmentForActivity(FragmentActivity act, Class fragmentClass) throws Throwable {
		try {
			if (fragmentClass.isAssignableFrom(Fragment.class)) {
				FragmentManager manager = act.getSupportFragmentManager();
				FragmentTransaction ft = manager.beginTransaction();
				Fragment frg = (Fragment) fragmentClass.newInstance();
				ft.add(frg, fragmentClass.getSimpleName());
				ft.show(frg);
				ft.commit();
			} else {
				throw (new Throwable("fragmentClass 不是一个v4 fragment的子类"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取订单号
	 * 
	 * @return
	 */
	public static String getOutTradeNo() {
		// ''.time().rand(100000,999999);
		long timestamp = System.currentTimeMillis();
		Random random = new Random();
		int s = random.nextInt(9999) % (9999 - 1000 + 1) + 1000;
		return "" + System.currentTimeMillis() + s;
	}

	/****************
	 * 
	 * 群号：网购排行榜用户群(481902374) 的 key 为： -KyQK4rOlUtXwdPyHqRI-SIqw7p3fJhP 调用
	 * joinQQGroup(-KyQK4rOlUtXwdPyHqRI-SIqw7p3fJhP) 即可发起手Q客户端申请加群
	 * 网购排行榜用户群(481902374)
	 * 
	 * @param key
	 *            由官网生成的key
	 * @return 返回true表示呼起手Q成功，返回fals表示呼起失败
	 ******************/
	public static boolean joinQQGroup(Context context, String key) {
		Intent intent = new Intent();
		if (StringUtils.isEmpty(key)) {// 控制判断
			key = "-KyQK4rOlUtXwdPyHqRI-SIqw7p3fJhP";
		}
		intent.setData(Uri
				.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D"
						+ key));
		// 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面
		// //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
		try {
			context.startActivity(intent);
			return true;
		} catch (Exception e) {
			// 未安装手Q或安装的版本不支持
			return false;
		}
	}

	/**
	 * 随机获取16位
	 * 
	 * @return
	 */
	public static String getRandom16() {
		String s = "";
		Random random = new Random();
		s += random.nextInt(9) + 1;
		for (int i = 0; i < 16 - 1; i++) {
			s += random.nextInt(10);
		}
		BigInteger bigInteger = new BigInteger(s);
		System.out.println(bigInteger);
		return bigInteger.toString();
	}

	/**
	 * 获取ua信息
	 * 
	 * @throws UnsupportedEncodingException
	 */
	public static String getUserUa(Context context) {
		WebView webview = new WebView(context);
		webview.layout(0, 0, 0, 0);
		String str = webview.getSettings().getUserAgentString();
		Logger.msg(str);
		return str;
	}

	/**
	 * 从清单文件中获取gameid与appid
	 * 
	 * agent处理： 
	 * 
	 * sdk 优先读自己的包内的agent 
	 * 		有：直接用，并且存入自己的agent存储区 
	 * 		没有：判断相应的app是否安装了？
	 * 			安装了：读自己的agent存储区 
	 * 					有：直接用 
	 * 					没有：读共享账号区的agent 
	 * 						有：存入自己的存储区，并使用 
	 * 						没有：真的没有了
	 * 			没有安装：真的没有agent
	 * 
	 * 
	 * app：
	 * 
	 * 优先读自己包内的agent 
	 * 	有：直接用，并且写入共享区agent (判断共享区的数据和要写人的数据不一致时才写入)
	 * 	没有：真的没有了，擦除之前存入共享区的agent
	 * 
	 * 
	 * @param context
	 * @return
	 */
	public static void getGameAndAppId(Context context) {

		PackageManager pm = context.getPackageManager();

		try {
			// 先通过反射获取
			// reflectGameAndAppId(context);
			// if (null != TTWAppService.gameid && null != TTWAppService.agentid
			// && null != TTWAppService.appid) {
			// return;
			// }
			// 在从清单文件中获取
			String channel = ChannelUtil.getChannel(context, ChannelUtil.AGENT_FILE);
			if (StringUtils.isEmpty(channel)) {
				channel = ChannelUtil.getChannel(context, ChannelUtil.AGENT_FILE2);
			}
			Log.e("channel:=======================", channel + "");
			// 在从清单文件中获取
			ApplicationInfo appinfo = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
			Bundle bundle = appinfo.metaData;
			if (null != bundle) {
				YTAppService.appid = (bundle.getInt("HS_APPID") == 0 ? -1 : bundle.getInt("HS_APPID")) + "";
				YTAppService.gameid = (bundle.getInt("HS_GAMEID") == 0 ? -1 : bundle.getInt("HS_GAMEID")) + "";
				YTAppService.agentid = bundle.getString("HS_AGENT");

				// YTAppService.clientId = "1";
				YTAppService.clientId = bundle.getInt("HS_CLIENTID") + "";
				// YTAppService.clientKey = "36ba570b88802fd382d65c627e15f697";
				YTAppService.clientKey = bundle.getString("HS_CLIENTKEY");

				if (null != channel && !"".equals(channel)) {
					YTAppService.agentid = channel;
				}
				Logger.msg("CHUYOU_____>appid：" + YTAppService.appid + "    gameid:" + YTAppService.gameid);
				Logger.msg("agentid:" + YTAppService.agentid);
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		SharedPreferences sp = context.getSharedPreferences("agent.sp", Context.MODE_PRIVATE);
		int loaclIntallCode=sp.getInt(AgentDbBean.INSTALL_CODE, 0);
		String localAgent=sp.getString(AgentDbBean.AGENT,null);
		if (TextUtils.isEmpty(YTAppService.agentid) || "0".equals(YTAppService.agentid)
				|| "default".equals(YTAppService.agentid)) {// 没有读到
			AgentDbBean agentDbBean=AgentDbDao.getInstance(context).getAgengDbBeanByPackageName(context.getPackageName());
			if(agentDbBean!=null){//外部有
				if(agentDbBean.getInstallCode()>loaclIntallCode){//从盒子安装的新的sdk
					YTAppService.agentid=agentDbBean.getAgent();
					sp.edit().putInt(AgentDbBean.INSTALL_CODE, agentDbBean.getInstallCode())
							.putString(AgentDbBean.AGENT, agentDbBean.getAgent()).commit();
					Log.i("hongliang", "从外部读取到了一个新的agent="+agentDbBean.getAgent());
				}else{
					Log.i("hongliang", "当前sdk不是从外部新安装的");
					if(!TextUtils.isEmpty(localAgent)){//本地有使用本地的
						YTAppService.agentid=localAgent;
						Log.i("hongliang", "从本地读到agent="+localAgent);
					}
				}
			}else{
				Log.i("hongliang", "外部没有");
				if(!TextUtils.isEmpty(localAgent)){//本地有使用本地的
					YTAppService.agentid=localAgent;
					Log.i("hongliang", "从本地读到agent="+localAgent);
				}
			}
//			if (ApkUtils.isInstallApp(context, Constants.APP_PACKAGE)) {// app安装了，可以从app中读取
//				SharedPreferences sp = context.getSharedPreferences("agent.sp", Context.MODE_PRIVATE);
//				String tempAgentId = sp.getString("agentid", null);
//				if (!TextUtils.isEmpty(tempAgentId)) {// 本地agentId有
//					YTAppService.agentid = tempAgentId;
//				} else {// 本地agentId没有
//					tempAgentId = AgentDao.getAgent();
//					if (!TextUtils.isEmpty(tempAgentId)) {// 共享区有
//						YTAppService.agentid = tempAgentId;
//						sp.edit().putString("agentid", YTAppService.agentid).commit();
//					}
//				}
//			}
		} else {// 有,存入自己的sp中
			sp.edit().putString(AgentDbBean.AGENT, YTAppService.agentid)
					.putInt(AgentDbBean.INSTALL_CODE, loaclIntallCode).commit();
			Log.i("hongliang", "从包内读到agent="+YTAppService.agentid);
		}
	}

	/**
	 * 通过反射获取gameid,appid,agent
	 * 
	 * @param context
	 */
	public static void reflectGameAndAppId(Context context) {
		try {
			Class<?> c = Class.forName("com.tiantianwan.game.sdk.TTWconfig");
			Method method_gameid = c.getDeclaredMethod("getGameId", Context.class);
			method_gameid.setAccessible(true);
			Method method_appid = c.getDeclaredMethod("getAppId", Context.class);
			method_appid.setAccessible(true);
			Method method_agent = c.getDeclaredMethod("getAgent", Context.class);
			method_agent.setAccessible(true);

			Object obj = c.newInstance();
			YTAppService.gameid = (String) method_gameid.invoke(obj, context);
			YTAppService.appid = (String) method_appid.invoke(obj, context);
			YTAppService.agentid = (String) method_agent.invoke(obj, context);
			Logger.msg("反射获取的tiantianwan_____>appid：" + YTAppService.appid + "    gameid:" + YTAppService.gameid);
			Logger.msg("agentid:" + YTAppService.agentid);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	public static String getTokenForFloat(String user_token) {
		return Md5Util.md5(Md5Util.md5(user_token + "float") + YTAppService.clientKey);
	}

	public static String getTokenForWebPay(String user_token, String pay_token) {
		return Md5Util.md5(Md5Util.md5(user_token + pay_token + "shenzhoufu") + YTAppService.clientKey);
	}

	public static boolean isWeixinAvilible(Context context) {
		final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
		List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
		if (pinfo != null) {
			for (int i = 0; i < pinfo.size(); i++) {
				String pn = pinfo.get(i).packageName;
				if (pn.equals("com.tencent.mm")) {
					return true;
				}
			}
		}

		return false;
	}

	/**
	 * 判断qq是否可用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isQQClientAvailable(Context context) {
		final PackageManager packageManager = context.getPackageManager();
		List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
		if (pinfo != null) {
			for (int i = 0; i < pinfo.size(); i++) {
				String pn = pinfo.get(i).packageName;
				if (pn.equals("com.tencent.mobileqq")) {
					return true;
				}
			}
		}
		return false;
	}
}
